<?php
// public/users/edit.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';
require_role('admin');

global $pdo;

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) { header('Location: /ldp/public/users/index.php'); exit; }

// Fetch user
$stmt = $pdo->prepare("SELECT id, name, email, role, status FROM users WHERE id = ?");
$stmt->execute([$id]);
$userRow = $stmt->fetch();
if (!$userRow) { set_flash('warning', 'User not found.'); header('Location: /ldp/public/users/index.php'); exit; }

$errors = [];
$name = $userRow['name'];
$email = $userRow['email'];
$role = $userRow['role'];
$status = $userRow['status'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  verify_csrf();
  $name = trim($_POST['name'] ?? '');
  $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL) ?: '';
  $role = $_POST['role'] ?? $role;
  $status = $_POST['status'] ?? $status;
  $password = $_POST['password'] ?? ''; // optional

  if ($name === '' || mb_strlen($name) < 3) $errors['name'] = 'Name must be at least 3 characters.';
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors['email'] = 'Valid email is required.';
  if (!in_array($role, ['admin','hr','trainer','employee'], true)) $errors['role'] = 'Invalid role.';
  if (!in_array($status, ['active','inactive'], true)) $errors['status'] = 'Invalid status.';

  // unique email (excluding current)
  if (empty($errors)) {
    $stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM users WHERE email = ? AND id <> ?");
    $stmt->execute([$email, $id]);
    if ((int)$stmt->fetch()['c'] > 0) $errors['email'] = 'Email already in use by another account.';
  }

  if (empty($errors)) {
    if ($password !== '') {
      if (mb_strlen($password) < 8) $errors['password'] = 'Password must be at least 8 characters.';
    }
  }

  if (empty($errors)) {
    if ($password !== '') {
      $hash = password_hash($password, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, role=?, status=?, password=? WHERE id=?");
      $stmt->execute([$name, $email, $role, $status, $hash, $id]);
    } else {
      $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, role=?, status=? WHERE id=?");
      $stmt->execute([$name, $email, $role, $status, $id]);
    }

    set_flash('success', 'User updated successfully.');
    header('Location: /ldp/public/users/index.php');
    exit;
  }
}

render_header('Edit User', 'users');
?>
<div class="card">
  <div class="card-body">
    <form method="post" autocomplete="off" novalidate>
      <?= csrf_field(); ?>

      <div class="form-group">
        <label class="form-required">Full Name</label>
        <input type="text" name="name" class="form-control <?= isset($errors['name'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($name) ?>">
        <?php if(isset($errors['name'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['name']) ?></div><?php endif; ?>
      </div>

      <div class="form-group">
        <label class="form-required">Email</label>
        <input type="email" name="email" class="form-control <?= isset($errors['email'])?'is-invalid':'' ?>" value="<?= htmlspecialchars($email) ?>">
        <?php if(isset($errors['email'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['email']) ?></div><?php endif; ?>
      </div>

      <div class="form-row">
        <div class="form-group col-md-6">
          <label class="form-required">Role</label>
          <select name="role" class="form-control <?= isset($errors['role'])?'is-invalid':'' ?>">
            <?php foreach (['employee','trainer','hr','admin'] as $opt): ?>
              <option value="<?= $opt ?>" <?= $role===$opt?'selected':'' ?>><?= ucfirst($opt) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if(isset($errors['role'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['role']) ?></div><?php endif; ?>
        </div>
        <div class="form-group col-md-6">
          <label class="form-required">Status</label>
          <select name="status" class="form-control <?= isset($errors['status'])?'is-invalid':'' ?>">
            <?php foreach (['active','inactive'] as $opt): ?>
              <option value="<?= $opt ?>" <?= $status===$opt?'selected':'' ?>><?= ucfirst($opt) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if(isset($errors['status'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['status']) ?></div><?php endif; ?>
        </div>
      </div>

      <div class="form-group">
        <label>New Password (optional)</label>
        <input type="password" name="password" class="form-control <?= isset($errors['password'])?'is-invalid':'' ?>" placeholder="Leave blank to keep current">
        <?php if(isset($errors['password'])): ?><div class="invalid-feedback"><?= htmlspecialchars($errors['password']) ?></div><?php endif; ?>
      </div>

      <div class="d-flex justify-content-between">
        <a href="/ldp/public/users/index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <button class="btn btn-primary"><i class="fas fa-save"></i> Update</button>
      </div>
    </form>
  </div>
</div>
<?php render_footer(); ?>
